﻿// Copyright (c) 2007-2021 西安交通信息投资营运有限公司 版权所有
// 作者:吕艳阳

using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace XCI.Core
{
    /// <summary>
    /// 对象一次性执行函数
    /// </summary>
    public class OnceAction
    {
        private readonly Dictionary<string, int> Actions = new Dictionary<string, int>();

        /// <summary>
        /// 执行一次性函数
        /// </summary>
        /// <param name="name">操作名称</param>
        /// <param name="callback">回调函数</param>
        public void Run(string name, Action callback)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
            if (callback == null) throw new ArgumentNullException(nameof(callback));
            if (Actions.ContainsKey(name)) return;
            Actions[name] = 1;
            callback.Invoke();
        }

        /// <summary>
        /// 异步执行一次性函数
        /// </summary>
        /// <param name="name">操作名称</param>
        /// <param name="callback">回调函数</param>
        public async Task RunAsync(string name, Func<Task> callback)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
            if (callback == null) throw new ArgumentNullException(nameof(callback));
            if (Actions.ContainsKey(name)) return;
            Actions[name] = 1;
            await callback.Invoke();
        }

        /// <summary>
        /// 是否包含指定名称的回调函数
        /// </summary>
        /// <param name="name">待查找的回调函数名称</param>
        /// <returns>如果存在则为 <see langword="true" />；否则为 <see langword="false" />。</returns>
        public bool Contains(string name)
        {
            return Actions.ContainsKey(name);
        }

        /// <summary>
        /// 移除指定名称的回调函数
        /// </summary>
        /// <param name="name">待移除的回调函数名称</param>
        /// <returns>如果成功找到并移除该元素，则为 <see langword="true" />；否则为 <see langword="false" />。 </returns>
        public bool Remove(string name)
        {
            return Actions.Remove(name);
        }
    }
}